package ar.edu.unrn.lia.bean.convert;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItems;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import ar.edu.unrn.lia.model.Role;

@ManagedBean(name = "roleConvert")
@RequestScoped
public class RoleConvert implements Converter {

	@Override
	public Object getAsObject(FacesContext ctx, UIComponent comp, String value) {

		if (value == null) {
			return null;
		}
		// Recupero la lista desde el componente
		List<Role> roles = (ArrayList<Role>) ((UISelectItems) comp
				.getChildren().get(0)).getValue();

		for (Role r : roles) {
			if (r.getId().toString().equals(value)) {
				return r;
			}

		}

		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
		return value instanceof Role ? ((Role) value).getId().toString() : "";
	}

}
